package com.nulldev.util.security.encryptAPI.impls.nacl_thirdparty;

import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Base64.Base64;
import com.nulldev.util.security.encryptAPI.Encryptor;
import com.nulldev.util.security.encryptAPI.impls.nacl_thirdparty.NaCl.SecretBox;

public class NaClSharedCipher extends Encryptor {
	private final NaCl.SecretBox box;
	private final byte[] key;

	public NaClSharedCipher(final String key) {
		super("encryptapi.tp.nacl_shared", new String[]
			{ "NaCl", "NACL", "nacl" }, key);
		this.box = new SecretBox(this.key = key.getBytes());
	}

	public NaClSharedCipher(final byte[] key) {
		super("encryptapi.tp.nacl_shared", new String[]
			{ "NaCl", "NACL", "nacl" }, key);
		this.box = new SecretBox(this.key = key);
	}

	@Override
	public byte[] encryptToBytes(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return this.box.box((byte[]) o);
		} else if (o instanceof String) {
			return this.box.box(((String) o).getBytes());
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String encrypt(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return Base64.encodeBase64String(this.box.box((byte[]) o));
		} else if (o instanceof String) {
			return Base64.encodeBase64String(this.box.box(((String) o).getBytes()));
		} else {
			throw new UnsupportedOperationException("encrypt() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String decrypt(String s) {
		return new String(this.box.open(Base64.decodeBase64(s)));
	}

	@Override
	public byte[] decryptToBytes(byte[] b) {
		return this.box.open(b);
	}

	@Override
	public byte[] getKey() {
		return this.key;
	}

	@Override
	public String getKeyAsString() {
		return new String(this.key);
	}
}
